package com.ly10111.customedittext.view;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ly10111.customedittext.R;
import com.ly10111.customedittext.ime.dict.DictBean;
import com.ly10111.customedittext.ime.dict.IDict;
import com.ly10111.customedittext.ime.dict.PyDict;
import com.ly10111.customedittext.ime.dict.ZyDict;

import java.util.ArrayList;
import java.util.HashMap;

public class KeyboardView extends LinearLayout implements View.OnClickListener, View.OnLongClickListener {

    public static final int inputType_zy = 1;
    public static final int inputType_py = 2;
    public static final int action_default = 10;
    public static final int action_123 = 11;
    public static final int action_abc = 12;
    public static final int action_space = 13;
    public static final int action_del = 14;
    public static final int action_enter = 15;
    public static final int action_hide = 16;
    public static final int click_short = 20;
    public static final int click_long = 21;
    private OnClickListener onClickListener = null;
    private LinearLayout keyboard_span;
    private EditText keyboard_word;
    private LinearLayout keyboard_phrase;
    private TextView keyboard_hide;
    private HashMap<String, String> codeMap = new HashMap<>();
    private IDict dict;
    private SoundPool soundPool;

    public KeyboardView(Context context) {
        super(context);
    }

    public KeyboardView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public KeyboardView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public KeyboardView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initSound(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            soundPool = new SoundPool.Builder().setMaxStreams(1).build();
        } else {
            soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        }
        soundPool.load(context, 1, 1);
    }

    private void initOnClickListener(EditText et) {
        onClickListener = new KeyboardView.OnClickListener(et) {

            @Override
            public void onClick(String text, int action, int click) {
                Log.d("===ce===", "KeyboardView.OnClickListener");
                switch (action) {
                    case KeyboardView.action_default:
                        if (getEt().getSelectionStart() == getEt().length())
                            getEt().getText().append(text);
                        else getEt().getText().insert(getEt().getSelectionStart(), text);
                        break;
                    case KeyboardView.action_123:
                        Toast.makeText(getContext(), "切换到数字键盘", Toast.LENGTH_SHORT).show();
                        break;
                    case KeyboardView.action_abc:
                        Toast.makeText(getContext(), "切换到英文键盘", Toast.LENGTH_SHORT).show();
                        break;
                    case KeyboardView.action_space:
                        if (getEt().getSelectionStart() == getEt().length())
                            getEt().getText().append(" ");
                        else getEt().getText().insert(getEt().getSelectionStart(), " ");
                        break;
                    case KeyboardView.action_del:
                        int length = getEt().getSelectionEnd();
                        if (length > 0) getEt().getText().delete(length - 1, length);
                        break;
                    case KeyboardView.action_enter:
                        Toast.makeText(getContext(), "换行或完成", Toast.LENGTH_SHORT).show();
                        break;
                    case KeyboardView.action_hide:
                        KeyboardView.this.setVisibility(View.GONE);
                        break;
                }
            }
        };
    }

    private void initZy(ViewGroup group) {
        LayoutInflater.from(group.getContext()).inflate(R.layout.keyboard_zy, group);
        keyboard_span = findViewById(R.id.keyboard_span);
        keyboard_word = findViewById(R.id.keyboard_word);
        keyboard_phrase = findViewById(R.id.keyboard_phrase);
        keyboard_hide = findViewById(R.id.keyboard_hide);
        keyboard_word.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0 && keyboard_word.getVisibility() != VISIBLE)
                    keyboard_word.setVisibility(VISIBLE);
                else if (editable.length() == 0 && keyboard_word.getVisibility() != INVISIBLE)
                    keyboard_word.setVisibility(INVISIBLE);
            }
        });
        if (dict != null) dict.close();
        dict = new ZyDict();
        dict.open(group.getContext());
        codeMap.clear();
        codeMap.putAll(dict.getDictCodeMap());
        setOnClick(group);
    }

    private void initPy(ViewGroup group) {
        LayoutInflater.from(group.getContext()).inflate(R.layout.keyboard_py, group);
        keyboard_span = findViewById(R.id.keyboard_span);
        keyboard_word = findViewById(R.id.keyboard_word);
        keyboard_phrase = findViewById(R.id.keyboard_phrase);
        keyboard_hide = findViewById(R.id.keyboard_hide);
        keyboard_word.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0 && keyboard_word.getVisibility() != VISIBLE)
                    keyboard_word.setVisibility(VISIBLE);
                else if (editable.length() == 0 && keyboard_word.getVisibility() != INVISIBLE)
                    keyboard_word.setVisibility(INVISIBLE);
            }
        });
        if (dict != null) dict.close();
        dict = new PyDict();
        dict.open(group.getContext());
        codeMap.clear();
        setOnClick(group);
    }

    private void setOnClick(ViewGroup group) {
        keyboard_hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (keyboard_phrase.getChildCount() > 0) {
                    keyboard_phrase.removeAllViews();
                    keyboard_hide.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_suggest_strip_scroll_down_arrow1, 0, 0, 0);
                } else onClickListener.onClick(null, action_hide, click_short);
            }
        });
        for (int i = 0; i < group.getChildCount(); i++) {
            View v = group.getChildAt(i);
            if (v instanceof ViewGroup) setOnClick((ViewGroup) v);
            else {
                v.setOnClickListener(this);
                v.setOnLongClickListener(this);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            Button button = (Button) v;
            String text = button.getText().toString();
            if (text.equals(v.getContext().getString(R.string.keycode_123)))
                onClickListener.onClick(text, action_123, click_short);
            else if (text.equals(v.getContext().getString(R.string.keycode_abc)))
                onClickListener.onClick(text, action_abc, click_short);
            else {
                //如果是1-0.,，。直接写到et，否则写到选择板
                if (text.equals(v.getContext().getString(R.string.keycode_0))
                        || text.equals(v.getContext().getString(R.string.keycode_1))
                        || text.equals(v.getContext().getString(R.string.keycode_2))
                        || text.equals(v.getContext().getString(R.string.keycode_3))
                        || text.equals(v.getContext().getString(R.string.keycode_4))
                        || text.equals(v.getContext().getString(R.string.keycode_5))
                        || text.equals(v.getContext().getString(R.string.keycode_6))
                        || text.equals(v.getContext().getString(R.string.keycode_7))
                        || text.equals(v.getContext().getString(R.string.keycode_8))
                        || text.equals(v.getContext().getString(R.string.keycode_9))
                        || text.equals(v.getContext().getString(R.string.keycode_doc))
                        || text.equals(v.getContext().getString(R.string.keycode_douhao))
                        || text.equals(v.getContext().getString(R.string.keycode_juhao)))
                    onClickListener.onClick(text, action_default, click_short);
                else {
                    //先判断是否是注音按键或字母按键
                    if (!codeMap.containsKey((int) text.charAt(0) + "") && !(text.charAt(0) >= 'A' && text.charAt(0) <= 'Z'))
                        return;
                    //查字典
                    if (text.charAt(0) >= 'A' && text.charAt(0) <= 'Z') text = text.toLowerCase();
                    keyboard_word.getText().append(text);
                    Log.d("===ce===", "char:" + text + "," + (int) text.charAt(0));
                    cursor(keyboard_word.getText().toString(), false, false);
                    return;
                }
            }
            keyboard_word.getText().clear();
        } else if (v instanceof ImageButton) {
            String text = (String) v.getTag();
            if (keyboard_span.getVisibility() == VISIBLE) {
                if (text.equals(v.getContext().getString(R.string.keycode_space))) {
                    if (keyboard_phrase.getChildCount() == 0)
                        onClickListener.onClick(text, action_space, click_short);
                    else keyboard_phrase.getChildAt(0).callOnClick();
                    keyboard_word.getText().clear();
                } else if (text.equals(v.getContext().getString(R.string.keycode_del))) {
                    int length = keyboard_word.getText().length();
                    if (length > 0) keyboard_word.getText().delete(length - 1, length);
                    else
                        onClickListener.onClick(keyboard_word.getText().toString(), action_del, click_short);
                    if (length > 1) cursor(keyboard_word.getText().toString(), false, false);
                    else keyboard_phrase.removeAllViews();
                } else if (text.equals(v.getContext().getString(R.string.keycode_enter))) {
                    onClickListener.onClick(keyboard_word.getText().toString(), action_default, click_short);
                    keyboard_word.getText().clear();
                }
            } else {
                if (text.equals(v.getContext().getString(R.string.keycode_space)))
                    onClickListener.onClick(text, action_space, click_short);
                else if (text.equals(v.getContext().getString(R.string.keycode_del)))
                    onClickListener.onClick(text, action_del, click_short);
                else if (text.equals(v.getContext().getString(R.string.keycode_enter)))
                    onClickListener.onClick(text, action_enter, click_short);
            }
        }
    }

    /**
     * 传入键盘显示文字
     *
     * @param text
     */
    private void cursor(String text, boolean isWord, boolean isPhrases) {
        Log.d("===ce===", "cursor:" + text);
        ArrayList<DictBean> list = dict.cursor(text, codeMap, isWord, isPhrases);
        keyboard_phrase.removeAllViews();
        for (DictBean dictBean : list) {
            TextView tv = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.keyboard_phrase, keyboard_phrase, false);
            tv.setText(dictBean.getWord());
            tv.setTag(dictBean);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DictBean dictBean1 = (DictBean) view.getTag();
                    onClickListener.onClick(dictBean1.getWord(), action_default, click_short);
                    keyboard_word.getText().clear();
                    //keyboard_phrase.removeAllViews();
                    //联想功能
                    dict.addUse(dictBean1);
                    Log.d("===ce===", "dictBean1:" + dictBean1.getWord());
                    cursor(dictBean1.getWord(), true, true);
                }
            });
            keyboard_phrase.addView(tv);
        }
        if (!isPhrases) return;
        if (list.size() > 0)
            keyboard_hide.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_suggest_strip_scroll_clear_arrow, 0, 0, 0);
        else
            keyboard_hide.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_suggest_strip_scroll_down_arrow1, 0, 0, 0);
    }

    @Override
    public boolean onLongClick(View v) {
        if (v instanceof ImageButton) {
            String text = (String) v.getTag();
            if (text.equals(v.getContext().getString(R.string.keycode_del)))
                onClickListener.onClick(text, action_del, click_long);
        }
        return true;
    }

    public void setInputType(int inputType, EditText et) {
        if (inputType == inputType_zy)
            initZy(this);
        else if (inputType == inputType_py)
            initPy(this);
        initOnClickListener(et);
    }

    @Override
    public void setVisibility(int visibility) {
        if (visibility == GONE && keyboard_span != null && keyboard_word != null && keyboard_phrase != null)
            removeAllViews();
        if (visibility == GONE && dict != null) dict.close();
        super.setVisibility(visibility);
    }

    public abstract class OnClickListener {
        private EditText et;

        public OnClickListener(EditText et) {
            this.et = et;
        }

        public EditText getEt() {
            return et;
        }

        abstract void onClick(String text, int action, int click);
    }
}
